package sd.qd.xiaoming.coffeedesk.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import sd.qd.xiaoming.coffeedesk.entity.CdDict;
import sd.qd.xiaoming.coffeedesk.service.CdDictService;

@Controller
@RequestMapping("/dict")
public class CdDictController {
    @Autowired
    private CdDictService cdDictService;

    @ResponseBody
    @RequestMapping("/change_pwd")
    public Object changePwd(@RequestParam("oldpwd") final String oldPwd,
            @RequestParam("newpwd") final String newPwd) {
        CdDict dicPwd = this.cdDictService.findByCode("pwd");
        Map<String, Object> result = new HashMap<String, Object>();
        if (!dicPwd.getName().equals(oldPwd)) {
            result.put("success", false);
            result.put("msg", "旧密码输入错误！");
            return result;
        }
        dicPwd.setName(newPwd);
        this.cdDictService.merge(dicPwd);
        result.put("success", true);
        return result;
    }
    
    @ResponseBody
    @RequestMapping("/change_username")
    public Object changeUserName(@RequestParam("username") final String username) {
        CdDict dicUsername = this.cdDictService.findByCode("username");
        dicUsername.setName(username);
        this.cdDictService.update(dicUsername);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", true);
        return result;
    }

    
    @ResponseBody
    @RequestMapping("/get_dict_by_code/{code}")
    public Object getValueByCode(@PathVariable("code") final String code) {
        return this.cdDictService.findByCode(code).getName();
    }

    @ResponseBody
    @RequestMapping("/login")
    public Object login(@RequestParam("username") final String username,
            @RequestParam("pwd") final String pwd) {
        CdDict dicUsername = this.cdDictService.findByCode("username");
        CdDict dicPwd = this.cdDictService.findByCode("pwd");
        Map<String, Object> result = new HashMap<String, Object>();
        if (!dicUsername.getName().equals(username)) {
            result.put("success", false);
            result.put("msg", "用户名或密码不正确！");
            return result;
        }
        if (!dicPwd.getName().equals(pwd)) {
            result.put("success", false);
            result.put("msg", "用户名或密码不正确！");
            return result;
        }
        result.put("success", true);
        return result;
    }

}
